﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using Facade.Excel;

namespace PeisongWeb.admin
{
    public partial class buyerModulusEdit : adminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlCompanyBind();
                rootCategoryBind();
                rptBind();
                priceStructureBind();

                // 权限判断
                if (hasPermission("FE",2))// 企业加价
                {
                    ACTOCategory.Enabled = true;
                    ACTOCompany.Enabled = true;
                }
                if (hasPermission("CF",2))// 系统加价
                {
                    ACTOProduct.Enabled = true;
                    ACTOCompany.Enabled = true;
                }
            }
        }

        private void priceStructureBind()
        {
            DataTable dt = logic.category.listWithNewParentByCompany(companyId);
            rptPriceStructure.DataSource = dt;
            rptPriceStructure.DataBind();
        }

        private void ddlCompanyBind()
        {
            DataTable dt = logic.company.listWithCompanyTypeIncludeTest();
            ddlCompany.DataSource = dt;
            ddlCompany.DataBind();
            ddlCompany.Items.Insert(0, new ListItem("-请选择采购商-", "-1"));

            ddlCompany2.DataSource = dt;
            ddlCompany2.DataBind();
            ddlCompany2.Items.Insert(0, new ListItem("-请选择采购商-", "-1"));

            if (companyId != 0)
            {
                ddlCompany.SelectedIndex = ddlCompany.Items.IndexOf(ddlCompany.Items.FindByValue(companyId.ToString()));
                ddlCompany.Enabled = false;

                ddlCompany2.SelectedIndex = ddlCompany2.Items.IndexOf(ddlCompany2.Items.FindByValue(companyId.ToString()));
                ddlCompany2.Enabled = false;
            }
        }

        private void rootCategoryBind()
        {
            DataTable dt = logic.category.getByParent(0);
            ddlRootCategory.DataSource = dt;
            ddlRootCategory.DataBind();
            ddlRootCategory.Items.Insert(0, new ListItem("-请选择大类-", "-1"));
        }

        private void subCategoryBind(int parentId)
        {
            DataTable dt = logic.category.getByParent(parentId);
            ddlSubCategory.DataSource = dt;
            ddlSubCategory.DataBind();
            ddlSubCategory.Items.Insert(0, new ListItem("-请选择小类-", "-1"));
        }

        protected void ddlRootCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlRootCategory.SelectedValue != "-1")
            {
                subCategoryBind(Convert.ToInt32(ddlRootCategory.SelectedValue));
            }
            AspNetPager1.CurrentPageIndex = 1;
            rptBind();
        }

        protected int companyId
        {
            get
            {
                int companyId = 0;
                if (!string.IsNullOrEmpty(Request.QueryString["companyId"]))
                {
                    int.TryParse(Request.QueryString["companyId"], out companyId);
                }
                else if (ddlCompany.SelectedValue != "-1")
                {
                    int.TryParse(ddlCompany.SelectedValue, out companyId);
                }
                else if (ddlCompany2.SelectedValue != "-1")
                {
                    int.TryParse(ddlCompany2.SelectedValue, out companyId);
                }
                return companyId;
            }
            set
            {
                companyId = value;
            }
        }

        private void rptBind()
        {
            if (companyId != 0)
            {
                StringBuilder where = new StringBuilder();
                where.AppendFormat("1=1 and companyId={0}", companyId);
                if (ddlRootCategory.SelectedValue != "-1" && !string.IsNullOrEmpty(ddlRootCategory.SelectedValue))
                    where.AppendFormat(" and parentCategoryId={0}", ddlRootCategory.SelectedValue);
                if (ddlSubCategory.SelectedValue != "-1" && !string.IsNullOrEmpty(ddlSubCategory.SelectedValue))
                    where.AppendFormat(" and categoryId={0}", ddlSubCategory.SelectedValue);
                if (!string.IsNullOrEmpty(txtProductName.Text))
                    where.AppendFormat(" and productName like '%{0}%'", txtProductName.Text);
                if (!string.IsNullOrEmpty(txtProductNo.Text))
                    where.AppendFormat(" and productNo='{0}'", txtProductNo.Text);

                DataSet ds = logic.priceStructure.select(where.ToString(), "productId", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
                AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                rpt_list.DataSource = ds.Tables[1];
                rpt_list.DataBind();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            rptBind();
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            rptBind();
        }

        protected void ddlCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            rptBind();
        }

        protected void ddlSubCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            rptBind();
        }

        // UpdatePanel异常处理
        protected void ResourceManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
        {
            ResourceManager1.AsyncPostBackErrorMessage = e.Exception.Message;
        }

        #region
        protected void linkExport_Click(object sender, EventArgs e)
        {
            DataTable dt = logic.product.listWithPriceByBuyer(companyId);
            string fileName = ddlCompany2.SelectedItem.Text + DateTime.Now.ToShortDateString() + "的价格表";

            ExportFacade facadeIntance = new ExportFacade();
            Dictionary<int, FormatStyle> formatOptions = new Dictionary<int, FormatStyle>();
            formatOptions.Add(4, FormatStyle.ToFix2);
            facadeIntance.ExportByWeb(dt,fileName,fileName+".xls",formatOptions,fileName);
        }

        protected void linkSearch2_Click(object sender, EventArgs e)
        {
            priceStructureBind();
        }

        protected void ddlCompany2_SelectedIndexChanged(object sender, EventArgs e)
        {
            priceStructureBind();
        }

        protected void btn_PriceStructureSave_Click(object sender, EventArgs e)
        {
            string categoryAutoPercentMap = hd_pricePercent.Value;
            logic.priceStructure.Init(logic.sysAdmin.AdminID, companyId, categoryAutoPercentMap);
            Library.Script.ClientMsgUrl("企业价格体系初始化成功!", "companyList.aspx");
            priceStructureBind();
            //ScriptManager.RegisterClientScriptBlock(this.UpdatePanel2, this.GetType(), "UpdatePanel2", "alert('企业价格体系初始化成功!');", true);
        }

        #endregion

        #region Tab3

        protected void rptMutiProducts_Command(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Choose")
            {
                ddlWhereClause3.SelectedValue = "1";
                string[] tArray = e.CommandArgument.ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                hdCurProductId.Value = tArray[0];
                txtFiledValue.Text = tArray[1];
                productAutoAddBind(false);
            }
        }

        protected void linkSearch3_Click(object sender, EventArgs e)
        {
            productAutoAddBind(true);
        }

        private void productAutoAddBind(bool enabledLike)
        {
            DataTable dt = new DataTable();

            if (ddlWhereClause3.SelectedValue == "1")
            {
                dt = logic.priceStructure.getProductAutoAddByProductNameOrProductNo("1", txtFiledValue.Text,enabledLike);
            }
            else if (ddlWhereClause3.SelectedValue == "2")
            {
                dt = logic.priceStructure.getProductAutoAddByProductNameOrProductNo("2", txtFiledValue.Text,enabledLike);
            }

            if (dt.Rows.Count > 1)
            {
                panel11.Visible = true;
                panel12.Visible = false;
                rptMutiProducts.DataSource = dt;
                rptMutiProducts.DataBind();
            }
            else if (dt.Rows.Count == 1)
            {
                panel11.Visible = false;
                panel12.Visible = true;

                DataRow row = dt.Rows[0];
                lbl3ProductName.Text = row["productName"].ToString();
                lbl3ProductAutoAdd.Text = hdCurProductAutoAdd.Value = string.Format("{0:F3}", row["productAutoAdd"]);
                hdCurProductId.Value = row["productId"].ToString();
            }
        }

        protected void btn3_Save_ProductAutoAdd_Click(object sender, EventArgs e)
        {
            decimal productAutoadd = 0m;
            decimal.TryParse(txt3ProductAutoAdd.Text, out productAutoadd);

            decimal oldProductAutoAdd = 0m;
            decimal.TryParse(hdCurProductAutoAdd.Value, out oldProductAutoAdd);

            int productId = 0;
            int.TryParse(hdCurProductId.Value, out productId);

            if (productId != 0)
            {
                logic.priceStructure.updateProductAutoAddBlock(logic.sysAdmin.AdminID, productId,oldProductAutoAdd,productAutoadd, chkApplyAllCompany.Checked);

                Library.Script.ClientMsg("保存成功!");

                productAutoAddBind(false);
            }
        }

        #endregion
    }
}
